<?php


namespace App\Models\CacheModel\zl5;


use App\Models\CacheModel\chat\HzQuestion;
use App\Models\CacheModel\chat\HzQuestionText;
use app\common\lib\Util;
use App\Models\Api\BaseCache;
use App\Models\Api\Recode;
use think\Env;
use think\Log;
use AstroTool\Cache\CacheManage;

class Zl5ExplainChat extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl5_explain_chat';

    protected $cacheModel = 'explain.explain_chat';

    /**
     * @param array $data
     * @return int
     */
    public function SaveData(array $data)
    {
        try
        {
            $id = $this->insertGetId($data);

            $this->listDataAdd($data['rid'], [$id => $id]);
        }
        catch (\Exception $e)
        {
            Log::write('Zl5ExplainChat model => SaveData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            $id = 0;
        }

        return (int)$id;
    }

    /**
     * 更新数据
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function UpdateData(int $id, array $data)
    {
        try
        {
            $this->where(['id' => $id])->update($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache($data);
            return true;
        }
        catch (\Exception $e)
        {
            Log::write('Zl5ExplainChat model => UpdateData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            // 获取未删除 的数据
            $data = $this
                ->where(['id' => ['in', $ids], 'status' => 1])
                ->column('id,uid,rid,qtype,type_id,title_id,content_id,state,extend,create_time,update_time', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'uid', 'rid', 'qtype', 'type_id', 'title_id', 'content_id', 'state', 'create_time', 'update_time']);

            if (isset($itemData['extend']))
            {
                $data[$index]['extend'] = $itemData['extend'] ? json_decode($itemData['extend'], true) : [];
            }
        }

        return $data;
    }

    /**
     * 获取列表数据
     * @param int $rid
     * @param int $maxId
     * @return array
     * @throws \Exception
     */
    public function getPageDatas(int $rid, int $maxId = 0)
    {
        $resData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $rid)
            ->setPage(-1)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($rid)
            {
                try
                {
                    $data = $this->where(['rid' => $rid, 'status' => 1])->order("id {$sortType}")->column('id');

                    $resData = [];
                    foreach ($data as $id)
                    {
                        $resData[$id] = ['id' => $id];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'id', 0);

        arsort($resData['data']);
        $allIds = array_keys($resData['data']);
        $ids = [];
        $surplusNum = 0;
        foreach ($allIds as $idItem)
        {
            if ($maxId > 0 && $idItem >= $maxId) continue;

            if (count($ids) >= 10)
            {
                $surplusNum++;
            } else
            {
                $ids[] = $idItem;
            }
        }

        $dataList = $this->batchGetInfoByIds($ids);

        $typeIds_1 = [];
        $titleIds_1 = [];
        $contentIds_1 = [];
        $titleIds_2 = [];
        foreach ($dataList as $dataItem)
        {
            if ($dataItem['qtype'] === 1)
            {
                $typeIds_1[] = $dataItem['type_id'];
                $titleIds_1[] = $dataItem['title_id'];
                $contentIds_1[] = $dataItem['content_id'];
            } else
            {
                $titleIds_2[] = $dataItem['title_id'];
            }
        }

        $typeList = $typeIds_1 ? (new Zl5ExplainType())->batchGetInfoByIds($typeIds_1) : [];
        $zl5ExplainTitleModel = new Zl5ExplainTitle();
        $questionList = $titleIds_1 ? $zl5ExplainTitleModel->batchGetInfoByIds($titleIds_1) : [];
        $zl5ExplainContentModel = new Zl5ExplainContent();
        $contentList = $contentIds_1 ? $zl5ExplainContentModel->batchGetInfoByIds($contentIds_1) : [];

        $questionList2 = $titleIds_2 ? (new HzQuestion())->batchGetInfoByIds($titleIds_2) : [];
        $hzQuestionConfig = config('hz_question');

        asort($ids);
        $resDataList = [];
        foreach ($ids as $idItem)
        {
            if (!isset($dataList[$idItem]))
            {
                continue;
            }
            $dataItem = $dataList[$idItem];
            if ($dataItem['qtype'] === 1)
            {
                $basis = $contentList[$dataItem['content_id']]['basis'];
                $linkList = [
                    [
                        'type' => 'basis',
                        'title' => $zl5ExplainContentModel->convertBasisToText($basis),
                        'basis' => $basis,
                        'target' => '',
                        'link' => '',
                    ]
                ];
                if (isset($questionList[$dataItem['title_id']]['extend']['recommend_goods']))
                {
                    foreach ($questionList[$dataItem['title_id']]['extend']['recommend_goods'] as $recommendGoodtem)
                    {
                        $linkList[] = [
                            'type' => 'shop',
                            'title' => $recommendGoodtem['title'],
                            'basis' => '',
                            'target' => $recommendGoodtem['target'],
                            'link' => $recommendGoodtem['link'],
                        ];
                    }
                }
                $title = isset($dataItem['extend']['type_id2']) ? $hzQuestionConfig[$dataItem['extend']['type_id2']] : $typeList[$dataItem['type_id']]['title'];

                $resDataList[] = [
                    'chat_id' => $dataItem['id'],
                    'title' => $title,
                    'question' => $questionList[$dataItem['title_id']]['title'],
                    'content' => $contentList[$dataItem['content_id']]['content'],
                    'link_list' => $linkList,
                    'state' => $dataItem['state'],
                    'create_time' => Util::timeToStr($dataItem['create_time']),
                ];
            } else
            {
                $resDataList[] = [
                    'chat_id' => $dataItem['id'],
                    'title' => $hzQuestionConfig[$dataItem['type_id']],
                    'question' => $questionList2[$dataItem['title_id']]['question'],
                    'content' => $this->getChatResultDataText($dataItem['extend']['result_data']),
                    'link_list' => [],
                    'state' => $dataItem['state'],
                    'create_time' => Util::timeToStr($dataItem['create_time']),
                ];
            }
        }

        $resData = [
            'total' => count($allIds),
            'surplus_num' => $surplusNum,
            'data' => $resDataList
        ];

        if ($resData['total'] === 0 || (count($resData['data']) > 0 && $resData['surplus_num'] === 0))
        {
            $recode = (new Recode())->getRecode(['id' => $rid]);
            $astroExplainData = (new \app\web\service\AstroExplain())->getAstroExplain($recode);
            //oss资源地址
            $oss = Env::get('host.photo');

            $firstData = [
                'chat_id' => 0,
                'title' => "HI，我是准准～\r\n让我先帮你从大的方向了解一下你的星盘，你是：",
                'content' => [
                    'title' => $astroExplainData['data'][0]['planet']['name'] . $astroExplainData['data'][0]['sign']['name'],
                    'icon' => $oss . $astroExplainData['data'][0]['planet']['en_icon'],
                    'content' => $astroExplainData['data'][0]['sign']['sing_text']
                ],
                'sun' => [
                    'name' => '太阳' . $astroExplainData['data'][0]['sign']['name'],
                    'abbreviation' => $astroExplainData['data'][0]['sign']['abbreviation'],
                ],
                'moon' => [
                    'name' => '月亮' . $astroExplainData['data'][1]['sign']['name'],
                    'abbreviation' => $astroExplainData['data'][1]['sign']['abbreviation'],
                ],
                'asc' => [
                    'name' => '上升' . $astroExplainData['data'][2]['sign']['name'],
                    'abbreviation' => $astroExplainData['data'][2]['sign']['abbreviation'],
                ],
                'link_list' => [
                    [
                        'type' => 'target',
                        'title' => '查看全部内容',
                        'basis' => '',
                        'target' => 'local',
                        'link' => "horoscope_analysis_info?rid={$rid}&tab_index=0&need_auth=1",
                    ]
                ],
                'create_time' => '',
            ];

            array_unshift($resData['data'], $firstData);
        }

        return $resData;
    }

    public function getChatResultDataText(array $resData)
    {
        $str = '';
        $hzQuestionTextModel = new HzQuestionText();
        foreach ($resData as $resDatum)
        {
            $textInfo = $hzQuestionTextModel->getTextById($resDatum);
            $str .= ($textInfo['content'] ?? '') . "\n";
        }
        return rtrim($str, "\n");
    }
}
